package tcu.ead2021.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import tcu.ead2021.entity.Invitation;
import tcu.ead2021.entity.R;
import tcu.ead2021.utils.MySQLUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

@WebServlet("/api/invitations/*")
public class InvitationServlet extends HttpServlet {

    private final List<Invitation> invitations;

    public InvitationServlet() {
        invitations = new ArrayList<>();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        MySQLUtils.LoginUser("123","222");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String Name = req.getParameter("Name");
        String startDay = req.getParameter("startDay");
        String days = req.getParameter("days");
        String Price = req.getParameter("Price");
        String Volume = req.getParameter("Volume");
        Invitation invitation = new Invitation(UUID.randomUUID().toString(), Name, LocalDate.parse(startDay, DateTimeFormatter.ISO_DATE), Integer.parseInt(days), Integer.parseInt(Price), Volume);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(R.ok(invitation));

        invitations.add(invitation);

        resp.getWriter().println(R.ok(invitations));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(R.ok(invitations));
        resp.getWriter().println(R.ok(invitations));
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        String id = url.substring(url.lastIndexOf("/") + 1, url.length());
        invitations.removeIf(invitation -> invitation.getId().equals(id));
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(R.ok(id));
        resp.getWriter().println(R.ok(id));
    }
}
